package org.example.forum.services.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.dao.ArticleReplyMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.ArticleReply;
import org.example.forum.services.IArticleReplyService;
import org.example.forum.services.IArticleService;
import org.example.forum.utils.StringUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private IArticleService articleService;

    @Override
    public void create(ArticleReply articleReply) {
        //非空校验
        if (articleReply == null
                || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtil.isEmpty(articleReply.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构造默认值写入数据库
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        articleReply.setCreateTime(new Date());
        articleReply.setUpdateTime(new Date());
        //写入数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新帖子表中的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        //打印成功体制
        log.info("帖子回复成功，article id = " + articleReply.getArticleId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if (articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO查询帖子列表
        List<ArticleReply> result = articleReplyMapper.selectByArticleId(articleId);
        //返回结果
        return result;
    }
}
